#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据格式适配器

确保后端API返回的数据格式与前端Mock数据格式完全一致
"""

from typing import Dict, Any, List
from datetime import datetime


class DataFormatAdapter:
    """数据格式适配器类"""
    
    @staticmethod
    def adapt_daily_sales(data: Dict[str, Any]) -> Dict[str, Any]:
        """适配日销售统计数据格式"""
        if not data.get('summary'):
            return {
                "total_amount": 0,
                "total_orders": 0,
                "avg_order_amount": 0
            }
        
        summary = data['summary']
        return {
            "total_amount": float(summary.get('total_amount', 0)),
            "total_orders": int(summary.get('order_count', 0)),  # order_count -> total_orders
            "avg_order_amount": float(summary.get('avg_order_amount', 0))
        }
    
    @staticmethod
    def adapt_weekly_sales(data: Dict[str, Any]) -> Dict[str, Any]:
        """适配周销售统计数据格式"""
        if not data.get('summary'):
            return {
                "total_amount": 0,
                "total_orders": 0,
                "avg_order_amount": 0
            }
        
        summary = data['summary']
        return {
            "total_amount": float(summary.get('total_amount', 0)),
            "total_orders": int(summary.get('order_count', 0)),  # order_count -> total_orders
            "avg_order_amount": float(summary.get('avg_order_amount', 0))
        }
    
    @staticmethod
    def adapt_monthly_sales(data: Dict[str, Any]) -> Dict[str, Any]:
        """适配月销售统计数据格式"""
        if not data.get('summary'):
            return {
                "total_amount": 0,
                "total_orders": 0,
                "avg_order_amount": 0
            }
        
        summary = data['summary']
        return {
            "total_amount": float(summary.get('total_amount', 0)),
            "total_orders": int(summary.get('order_count', 0)),  # order_count -> total_orders
            "avg_order_amount": float(summary.get('avg_order_amount', 0))
        }
    
    @staticmethod
    def adapt_comprehensive_stats(data: Dict[str, Any]) -> Dict[str, Any]:
        """适配综合统计数据格式"""
        # 从各个模块中提取总数据
        total_products = 0
        total_customers = 0
        total_orders = 0
        
        # 从月度数据中获取
        if data.get('monthly', {}).get('summary'):
            monthly = data['monthly']['summary']
            total_orders = int(monthly.get('order_count', 0))
            total_customers = int(monthly.get('customer_count', 0))
        
        # 从热销商品中获取商品数量
        if data.get('top_products', {}).get('statistics'):
            stats = data['top_products']['statistics']
            total_products = int(stats.get('total_products', 0))
        
        return {
            "total_products": total_products,
            "total_customers": total_customers,
            "total_orders": total_orders
        }
    
    @staticmethod
    def adapt_top_products(data: Dict[str, Any]) -> List[Dict[str, Any]]:
        """适配热销商品排行数据格式"""
        if not data.get('products'):
            return []
        
        adapted_products = []
        for item in data['products']:
            adapted_products.append({
                "product_name": item.get('goods_name', ''),  # goods_name -> product_name
                "sales_quantity": int(item.get('total_sold', 0)),  # total_sold -> sales_quantity
                "sales_amount": float(item.get('total_sales_amount', 0)),  # total_sales_amount -> sales_amount
                "percentage": float(item.get('sales_percentage', 0)) / 100  # 转换为小数形式
            })
        
        return adapted_products
    
    @staticmethod
    def adapt_sales_curve(data: Dict[str, Any]) -> List[Dict[str, Any]]:
        """适配销售曲线数据格式"""
        if not data.get('curve_data'):
            return []
        
        adapted_curve = []
        for item in data['curve_data']:
            adapted_curve.append({
                "date": str(item.get('period', '')),  # period -> date
                "total_amount": float(item.get('total_amount', 0)),
                "total_orders": int(item.get('order_count', 0))  # order_count -> total_orders
            })
        
        return adapted_curve
    
    @staticmethod
    def format_frontend_response(endpoint: str, original_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        统一格式化前端响应数据
        
        Args:
            endpoint: API端点类型 (daily/weekly/monthly/comprehensive/top_products/sales_curve)
            original_data: 原始后端数据
            
        Returns:
            格式化后的前端兼容数据
        """
        base_response = {
            "code": 200,
            "message": original_data.get('message', '获取成功'),
        }
        
        if not original_data.get('success', False):
            base_response.update({
                "code": 400,
                "message": original_data.get('message', '获取失败'),
                "data": None
            })
            return base_response
        
        data = original_data.get('data', {})
        
        if endpoint == 'daily':
            adapted_data = DataFormatAdapter.adapt_daily_sales(data)
        elif endpoint == 'weekly':
            adapted_data = DataFormatAdapter.adapt_weekly_sales(data)
        elif endpoint == 'monthly':
            adapted_data = DataFormatAdapter.adapt_monthly_sales(data)
        elif endpoint == 'comprehensive':
            adapted_data = DataFormatAdapter.adapt_comprehensive_stats(data)
        elif endpoint == 'top_products':
            adapted_data = DataFormatAdapter.adapt_top_products(data)
        elif endpoint == 'sales_curve':
            adapted_data = DataFormatAdapter.adapt_sales_curve(data)
        else:
            # 原数据保持不变
            adapted_data = data
        
        base_response['data'] = adapted_data
        return base_response
    
    @staticmethod
    def create_mock_compatible_endpoints():
        """
        创建与Mock数据完全兼容的端点映射
        
        Returns:
            端点映射字典
        """
        return {
            'daily_sales': {
                'endpoint': 'daily',
                'mock_structure': {
                    'total_amount': 0,
                    'total_orders': 0,
                    'avg_order_amount': 0
                }
            },
            'weekly_sales': {
                'endpoint': 'weekly',
                'mock_structure': {
                    'total_amount': 0,
                    'total_orders': 0,
                    'avg_order_amount': 0
                }
            },
            'monthly_sales': {
                'endpoint': 'monthly',
                'mock_structure': {
                    'total_amount': 0,
                    'total_orders': 0,
                    'avg_order_amount': 0
                }
            },
            'comprehensive_stats': {
                'endpoint': 'comprehensive',
                'mock_structure': {
                    'total_products': 0,
                    'total_customers': 0,
                    'total_orders': 0
                }
            },
            'top_products': {
                'endpoint': 'top_products',
                'mock_structure': [{
                    'product_name': '',
                    'sales_quantity': 0,
                    'sales_amount': 0,
                    'percentage': 0.0
                }]
            },
            'sales_curve': {
                'endpoint': 'sales_curve',
                'mock_structure': [{
                    'date': '',
                    'total_amount': 0,
                    'total_orders': 0
                }]
            }
        } 